package com.sjgs.gis.web.rest;

import com.sjgs.gis.web.errors.BadRequestAlertException;
import com.sjgs.gis.service.WarService;
import com.sjgs.gis.service.dto.WarDTO;
import com.sjgs.gis.service.dto.WarCriteria;
import com.sjgs.gis.service.WarQueryService;

import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing {@link com.sjgs.gis.domain.War}.
 */
@RestController
@RequestMapping("/api")
public class WarResource {

    private final Logger log = LoggerFactory.getLogger(WarResource.class);

    private static final String ENTITY_NAME = "geoserverportalWar";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final WarService warService;

    private final WarQueryService warQueryService;

    public WarResource(WarService warService, WarQueryService warQueryService) {
        this.warService = warService;
        this.warQueryService = warQueryService;
    }

    /**
     * {@code POST  /wars} : Create a new war.
     *
     * @param warDTO the warDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new warDTO, or with status {@code 400 (Bad Request)} if the war has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/wars")
    public ResponseEntity<WarDTO> createWar(@Valid @RequestBody WarDTO warDTO) throws URISyntaxException {
        log.debug("REST request to save War : {}", warDTO);
        if (warDTO.getId() != null) {
            throw new BadRequestAlertException("A new war cannot already have an ID", ENTITY_NAME, "idexists");
        }
        WarDTO result = warService.save(warDTO);
        return ResponseEntity.created(new URI("/api/wars/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /wars} : Updates an existing war.
     *
     * @param warDTO the warDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated warDTO,
     * or with status {@code 400 (Bad Request)} if the warDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the warDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/wars")
    public ResponseEntity<WarDTO> updateWar(@Valid @RequestBody WarDTO warDTO) throws URISyntaxException {
        log.debug("REST request to update War : {}", warDTO);
        if (warDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        WarDTO result = warService.save(warDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, warDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code GET  /wars} : get all the wars.
     *
     * @param pageable the pagination information.
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of wars in body.
     */
    @GetMapping("/wars")
    public ResponseEntity<List<WarDTO>> getAllWars(WarCriteria criteria, Pageable pageable) {
        log.debug("REST request to get Wars by criteria: {}", criteria);
        Page<WarDTO> page = warQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /wars/count} : count all the wars.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
     */
    @GetMapping("/wars/count")
    public ResponseEntity<Long> countWars(WarCriteria criteria) {
        log.debug("REST request to count Wars by criteria: {}", criteria);
        return ResponseEntity.ok().body(warQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /wars/:id} : get the "id" war.
     *
     * @param id the id of the warDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the warDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/wars/{id}")
    public ResponseEntity<WarDTO> getWar(@PathVariable Long id) {
        log.debug("REST request to get War : {}", id);
        Optional<WarDTO> warDTO = warService.findOne(id);
        return ResponseUtil.wrapOrNotFound(warDTO);
    }

    /**
     * {@code DELETE  /wars/:id} : delete the "id" war.
     *
     * @param id the id of the warDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/wars/{id}")
    public ResponseEntity<Void> deleteWar(@PathVariable Long id) {
        log.debug("REST request to delete War : {}", id);
        warService.delete(id);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
    }
}
